import React from 'react';
import { useI18n } from '@/utils/in18';
import { request } from '@/utils/request';
import InformationCardPC from '../informationCard_Pc/informationCard_PC';

type ListFilters = { keyword?: string; race?: string; category?: string; origin?: string } | undefined;

type CardItem = { id: number; title: string; desc?: string; src?: string; raw?: any; role_prompt: any };

const ImageWithSkeleton: React.FC<{ src?: string; alt?: string; className?: string; style?: React.CSSProperties; priority?: boolean }> = ({ src, alt, className, style, priority }) => {
  let cache: Record<string, boolean> = {};
  if (typeof window !== 'undefined') {
    (window as any).__IMG_LOADED_CACHE = (window as any).__IMG_LOADED_CACHE || {};
    cache = (window as any).__IMG_LOADED_CACHE as Record<string, boolean>;
  }
  const initialLoaded = src ? Boolean(cache[src]) : false;
  const [loaded, setLoaded] = React.useState<boolean>(initialLoaded);
  const imgRef = React.useRef<HTMLImageElement | null>(null);
  const onLoad = () => {
    if (src && cache) cache[src] = true;
    setLoaded(true);
  };
  // 兜底：避免弱网/某些机型懒加载迟迟不触发，4秒后结束骨架
  React.useEffect(() => {
    if (!loaded && src) {
      const id = window.setTimeout(() => setLoaded(true), 4000);
      return () => window.clearTimeout(id);
    }
  }, [src, loaded]);
  // 首屏高优先级
  React.useEffect(() => {
    try { if (priority && imgRef.current) { (imgRef.current as any).fetchPriority = 'high'; } } catch {}
  }, [priority]);
  return (
    <div className='absolute inset-0 w-full h-full overflow-hidden'>
      <div className={`absolute inset-0 bg-gradient-to-br from-gray-800 via-gray-700 to-gray-900 animate-pulse ${loaded ? 'opacity-0' : 'opacity-100'} transition-opacity duration-300`} />
      {src ? (
        <img
          ref={imgRef}
          src={src}
          alt={alt}
          loading={priority ? 'eager' : 'lazy'}
          decoding={priority ? 'sync' as any : 'async'}
          width={540}
          height={960}
          sizes={'(max-width: 640px) 50vw, (max-width: 1280px) 25vw, 20vw'}
          onLoad={onLoad}
          onError={onLoad}
          className={`${className || ''} ${loaded ? 'opacity-100' : 'opacity-0'} absolute inset-0 w-full h-full object-cover transition-opacity duration-500 ease-in-out`}
          style={{ willChange: 'opacity, transform', ...style }}
        />
      ) : null}
    </div>
  );
};

type CardsPCProps = {
  onCardClick?: (card: CardItem) => void;
  filters?: ListFilters;
};

const CardsPC: React.FC<CardsPCProps> = ({ onCardClick, filters }) => {
  const { locale, t } = useI18n();
  const [infoVisible, setInfoVisible] = React.useState<boolean>(false);
  const [infoCard, setInfoCard] = React.useState<CardItem | null>(null);
  const [items, setItems] = React.useState<CardItem[]>([]);
  const [page, setPage] = React.useState<number>(1);
  const pageSize = 8;
  const loadingRef = React.useRef<boolean>(false);
  const noMoreRef = React.useRef<boolean>(false);
  const seenIdsRef = React.useRef<Set<number>>(new Set());

  const fetchPage = React.useCallback(async (targetPage: number, replace = false) => {
    if (loadingRef.current) return;
    if (noMoreRef.current && !replace) return;
    loadingRef.current = true;
    try {
      const effective = filters;
      const payload: any = {
        search: effective && typeof effective.keyword === 'string' && effective.keyword.trim() ? effective.keyword.trim() : '',
        category: effective && typeof effective.category === 'string' ? effective.category : '',
        race: effective && typeof effective.race === 'string' ? effective.race : '',
        origin: effective && typeof effective.origin === 'string' ? effective.origin : '',
        name: '',
        sort: 'likes',
        page: targetPage,
        page_size: pageSize,
        language: locale || 'ey',
        information: ['image_url', 'name', 'likes', 'role_prompt'],
      };
      // 
      const res = await request.post('/api/template/getTemplatesRoute', payload);
      if (res?.data?.success === true) {
        const data = Array.isArray(res.data.data) ? res.data.data : [];
        if (replace) {
          seenIdsRef.current = new Set();
        }
        const next: CardItem[] = [];
        for (const it of data) {
          const id = typeof it?.id === 'number' ? it.id : undefined;
          if (typeof id !== 'number') continue;
          if (seenIdsRef.current.has(id)) continue;
          seenIdsRef.current.add(id);
          const url = String(it?.image_url ?? '').trim();
          if (!url) continue; // 过滤无效图片
          const title = String(it?.name ?? '');
          next.push({ id, title, src: url, raw: it, role_prompt: it?.role_prompt });
        }
        setItems((prev) => replace ? next : prev.concat(next));
        setPage(targetPage);
        if (data.length < pageSize) {
          noMoreRef.current = true;
        } else {
          noMoreRef.current = false;
        }
      }
    } catch (e) {
      // ignore
    } finally {
      loadingRef.current = false;
    }
  }, [filters, locale]);

  React.useEffect(() => {
    // 初次加载或筛选变化：重置并请求第一页
    noMoreRef.current = false;
    fetchPage(1, true);
  }, [filters, fetchPage]);

  React.useEffect(() => {
    const container = document.getElementById('app-content-scroll');
    const handleScroll = () => {
      try {
        if (loadingRef.current || noMoreRef.current) return;
        if (!container) return;
        const scrollTop = container.scrollTop;
        const winH = container.clientHeight;
        const docH = container.scrollHeight;
        if (scrollTop + winH >= docH - 200) {
          fetchPage(page + 1, false);
        }
      } catch (e) { }
    };
    if (container) {
      container.addEventListener('scroll', handleScroll, { passive: true } as any);
    }
    return () => {
      try { container?.removeEventListener('scroll', handleScroll as any); } catch { }
    };
  }, [page, fetchPage]);

  return (
    <div className="relative w-full">
      <div className='w-full'>
        <ul className='grid gap-2 grid-cols-2 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-4'>
          {items.map((item, idx) => (
            <li
              key={item.id}
              onClick={(e) => {
                e.stopPropagation();
                try { setInfoCard(item); setInfoVisible(true); } catch {}
                onCardClick && onCardClick(item);
              }}
              className={'cursor-pointer group rounded-[1rem] overflow-hidden bg-white dark:bg-[#1c1c1c] shadow'}
            >
              <div className={'relative w-full '} style={{ paddingBottom: '177.78%' }}>
                <ImageWithSkeleton
                  src={item.src}
                  alt={`img-${item.id}`}
                  priority={idx < 8}
                  className='transform transition-transform duration-300 ease-in-out group-hover:scale-105'
                />
                <div className='absolute left-0 right-0 bottom-0 px-3 py-2 bg-gradient-to-t from-black/70 to-transparent'>
                  <div className='text-sm text-white font-medium truncate'>{item.title}</div>
                  {/* 喜欢数量  */}
                  {/* <div className='text-sm text-white font-medium truncate'>{item.likes}</div> */}
                </div>
              </div>
            </li>
          ))}
        </ul>
        <div className='w-full flex items-center justify-center py-4 text-sm text-gray-400'>
          {loadingRef.current ? t('home.loading') : (noMoreRef.current ? t('home.no_more') : '')}
        </div>
      </div>
      {infoVisible && (
        <InformationCardPC visible={infoVisible} card={infoCard} onClose={() => { setInfoVisible(false); setInfoCard(null); }} />
      )}
    </div>
  );
};

export default CardsPC;


